package org.example.weboj.controller;

import org.example.weboj.dto.*;
import org.example.weboj.service.DebugService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/debug")
public class DebugController {

    @Autowired
    private DebugService debugService;

    /**
     * 启动调试会话
     */
    @PostMapping("/start")
    public ResponseEntity<?> startDebugSession(@RequestBody Map<String, Object> request) {
        try {
            String code = (String) request.get("code");
            String language = (String) request.get("language");
            String input = (String) request.get("input");
            
            if (code == null || code.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "Code is required"));
            }
            
            if (language == null || language.trim().isEmpty()) {
                language = "python"; // 默认为Python
            }
            
            // 生成会话ID
            String sessionId = UUID.randomUUID().toString();
            
            // 启动调试会话
            DebugSession session = debugService.startDebugSession(sessionId, code, language, input);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "sessionId", sessionId,
                "message", "Debug session started successfully",
                "session", session
            ));
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to start debug session: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取调试会话信息
     */
    @GetMapping("/session/{sessionId}")
    public ResponseEntity<?> getDebugSession(@PathVariable String sessionId) {
        try {
            DebugSession session = debugService.getDebugSession(sessionId);
            if (session == null) {
                return ResponseEntity.notFound().build();
            }
            return ResponseEntity.ok(session);
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to get debug session: " + e.getMessage()
            ));
        }
    }

    /**
     * 设置断点
     */
    @PostMapping("/session/{sessionId}/breakpoints")
    public ResponseEntity<?> setBreakpoints(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> request) {
        try {
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> breakpointMaps = (List<Map<String, Object>>) request.get("breakpoints");
            
            List<Breakpoint> breakpoints = breakpointMaps.stream()
                .map(map -> {
                    Breakpoint bp = new Breakpoint();
                    bp.setLine((Integer) map.get("line"));
                    bp.setEnabled(true);
                    return bp;
                })
                .toList();
            
            debugService.setBreakpoints(sessionId, breakpoints);
            
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Breakpoints set successfully",
                "breakpoints", breakpoints
            ));
            
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to set breakpoints: " + e.getMessage()
            ));
        }
    }

    /**
     * 继续执行
     */
    @PostMapping("/session/{sessionId}/continue")
    public ResponseEntity<?> continueExecution(@PathVariable String sessionId) {
        try {
            debugService.continueExecution(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Execution continued"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to continue execution: " + e.getMessage()
            ));
        }
    }

    /**
     * 单步执行
     */
    @PostMapping("/session/{sessionId}/step")
    public ResponseEntity<?> stepOver(@PathVariable String sessionId) {
        try {
            debugService.stepOver(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Step over executed"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to step over: " + e.getMessage()
            ));
        }
    }

    /**
     * 步入执行
     */
    @PostMapping("/session/{sessionId}/stepIn")
    public ResponseEntity<?> stepInto(@PathVariable String sessionId) {
        try {
            debugService.stepInto(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Step into executed"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to step into: " + e.getMessage()
            ));
        }
    }

    /**
     * 步出执行
     */
    @PostMapping("/session/{sessionId}/stepOut")
    public ResponseEntity<?> stepOut(@PathVariable String sessionId) {
        try {
            debugService.stepOut(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Step out executed"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to step out: " + e.getMessage()
            ));
        }
    }

    /**
     * 暂停执行
     */
    @PostMapping("/session/{sessionId}/pause")
    public ResponseEntity<?> pauseExecution(@PathVariable String sessionId) {
        try {
            debugService.pauseExecution(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Execution paused"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to pause execution: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取调用栈
     */
    @GetMapping("/session/{sessionId}/stackTrace")
    public ResponseEntity<?> getStackTrace(@PathVariable String sessionId) {
        try {
            List<StackFrame> stackFrames = debugService.getStackTrace(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "stackFrames", stackFrames
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to get stack trace: " + e.getMessage()
            ));
        }
    }

    /**
     * 获取变量
     */
    @GetMapping("/session/{sessionId}/variables")
    public ResponseEntity<?> getVariables(
            @PathVariable String sessionId,
            @RequestParam(defaultValue = "0") int frameId) {
        try {
            List<DebugVariable> variables = debugService.getVariables(sessionId, frameId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "variables", variables
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to get variables: " + e.getMessage()
            ));
        }
    }

    /**
     * 求值表达式
     */
    @PostMapping("/session/{sessionId}/evaluate")
    public ResponseEntity<?> evaluateExpression(
            @PathVariable String sessionId,
            @RequestBody Map<String, Object> request) {
        try {
            String expression = (String) request.get("expression");
            if (expression == null || expression.trim().isEmpty()) {
                return ResponseEntity.badRequest().body(Map.of("error", "Expression is required"));
            }
            
            String result = debugService.evaluateExpression(sessionId, expression);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "result", result
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to evaluate expression: " + e.getMessage()
            ));
        }
    }

    /**
     * 终止调试会话
     */
    @PostMapping("/session/{sessionId}/terminate")
    public ResponseEntity<?> terminateSession(@PathVariable String sessionId) {
        try {
            debugService.terminateDebugSession(sessionId);
            return ResponseEntity.ok(Map.of(
                "success", true,
                "message", "Debug session terminated"
            ));
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body(Map.of(
                "error", "Failed to terminate session: " + e.getMessage()
            ));
        }
    }
} 